"""问卷星问卷处理模块"""
import requests
import re
import time
from typing import Dict, Any, Optional
from urllib.parse import urlparse, parse_qs
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from utils.logger import get_logger

logger = get_logger()


class QuestionnaireHandler:
    """问卷星问卷处理器"""
    
    def __init__(self, url: str, user_info: Dict[str, str]):
        """
        初始化问卷处理器
        
        Args:
            url: 问卷链接
            user_info: 用户信息字典，包含 name, student_id, class_name, phone
        """
        self.url = url
        self.user_info = user_info
        self.session = requests.Session()
        
        # 设置请求头，模拟真实浏览器
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1'
        })
        
        self.activity_id = None
        self.form_data = {}
    
    def extract_activity_id(self) -> bool:
        """
        从URL中提取活动ID
        
        Returns:
            是否成功提取
        """
        logger.info("正在提取问卷活动ID...")
        
        try:
            # 尝试从URL参数中提取
            parsed_url = urlparse(self.url)
            query_params = parse_qs(parsed_url.query)
            
            # 常见的问卷星参数名
            possible_params = ['activityId', 'activity', 'id', 'aid']
            
            for param in possible_params:
                if param in query_params:
                    self.activity_id = query_params[param][0]
                    logger.info(f"成功提取活动ID：{self.activity_id}")
                    return True
            
            # 尝试从路径中提取
            path_match = re.search(r'/[mh]?j?q?/(\d+)', parsed_url.path)
            if path_match:
                self.activity_id = path_match.group(1)
                logger.info(f"从路径中提取活动ID：{self.activity_id}")
                return True
            
            logger.warning("无法从URL中提取活动ID，将尝试访问页面获取")
            return self._extract_from_page()
            
        except Exception as e:
            logger.error(f"提取活动ID时发生错误：{e}", exc_info=True)
            return False
    
    def _extract_from_page(self) -> bool:
        """
        从页面HTML中提取活动ID
        
        Returns:
            是否成功提取
        """
        try:
            logger.info("正在访问问卷页面...")
            response = self.session.get(self.url, timeout=10)
            
            if response.status_code != 200:
                logger.error(f"访问问卷页面失败，状态码：{response.status_code}")
                return False
            
            # 尝试从页面中提取活动ID
            patterns = [
                r'activityId["\']?\s*[:=]\s*["\']?(\d+)',
                r'activity["\']?\s*[:=]\s*["\']?(\d+)',
                r'data-activity["\']?\s*=\s*["\']?(\d+)',
            ]
            
            for pattern in patterns:
                match = re.search(pattern, response.text)
                if match:
                    self.activity_id = match.group(1)
                    logger.info(f"从页面中提取活动ID：{self.activity_id}")
                    return True
            
            logger.error("无法从页面中提取活动ID")
            return False
            
        except Exception as e:
            logger.error(f"访问页面时发生错误：{e}", exc_info=True)
            return False
    
    def prepare_form_data(self, custom_answers: Dict[str, Any] = None) -> Dict[str, Any]:
        """
        准备表单数据
        
        Args:
            custom_answers: 自定义答案字典（用于固定题目的答案）
        
        Returns:
            表单数据字典
        """
        logger.info("正在准备表单数据...")
        
        # 基础用户信息
        self.form_data = {
            'activityId': self.activity_id,
            'submittype': '1',
            'ktimes': '1',
        }
        
        # 添加用户信息（根据实际问卷字段名调整）
        # 这里使用通用的字段编号格式，实际使用时可能需要抓包确定
        user_fields = {
            '1': self.user_info.get('name', ''),          # 假设第1题是姓名
            '2': self.user_info.get('student_id', ''),     # 假设第2题是学号
            '3': self.user_info.get('class_name', ''),     # 假设第3题是班级
            '4': self.user_info.get('phone', ''),          # 假设第4题是手机号
        }
        
        self.form_data.update(user_fields)
        
        # 添加自定义答案
        if custom_answers:
            self.form_data.update(custom_answers)
        
        logger.info(f"表单数据准备完成：{len(self.form_data)} 个字段")
        return self.form_data
    
    def submit(self) -> bool:
        """
        提交问卷
        
        Returns:
            是否提交成功
        """
        logger.info("=" * 50)
        logger.info("开始提交问卷...")
        logger.info(f"提交时间：{time.strftime('%Y-%m-%d %H:%M:%S')}")
        
        if not self.activity_id:
            logger.error("活动ID未设置，无法提交")
            return False
        
        if not self.form_data:
            logger.error("表单数据未准备，无法提交")
            return False
        
        try:
            # 问卷星提交API（可能需要根据实际情况调整）
            submit_url = f"https://www.wjx.cn/joinnew/processjq.aspx?activityid={self.activity_id}"
            
            # 设置Referer
            self.session.headers['Referer'] = self.url
            
            logger.info(f"提交URL：{submit_url}")
            logger.debug(f"提交数据：{self.form_data}")
            
            # 发送POST请求
            response = self.session.post(
                submit_url,
                data=self.form_data,
                timeout=10,
                allow_redirects=True
            )
            
            logger.info(f"响应状态码：{response.status_code}")
            logger.debug(f"响应内容：{response.text[:500]}")
            
            # 判断是否提交成功
            if response.status_code == 200:
                # 问卷星通常返回包含特定关键词的页面
                success_keywords = ['提交成功', '感谢您的参与', 'success', '已提交']
                
                for keyword in success_keywords:
                    if keyword in response.text:
                        logger.info("✓ 问卷提交成功！")
                        return True
                
                # 检查是否有错误提示
                error_keywords = ['失败', '错误', 'error', '已结束', '已满']
                for keyword in error_keywords:
                    if keyword in response.text:
                        logger.error(f"✗ 问卷提交失败：检测到关键词 '{keyword}'")
                        return False
                
                logger.warning("无法确定提交状态，请检查响应内容")
                return False
            else:
                logger.error(f"✗ 提交失败，HTTP状态码：{response.status_code}")
                return False
                
        except requests.exceptions.Timeout:
            logger.error("✗ 提交超时")
            return False
        except requests.exceptions.RequestException as e:
            logger.error(f"✗ 网络请求错误：{e}", exc_info=True)
            return False
        except Exception as e:
            logger.error(f"✗ 提交时发生未知错误：{e}", exc_info=True)
            return False
        finally:
            logger.info("=" * 50)
    
    def run(self, custom_answers: Dict[str, Any] = None) -> bool:
        """
        运行完整流程：提取ID -> 准备数据 -> 提交
        
        Args:
            custom_answers: 自定义答案
        
        Returns:
            是否成功
        """
        if not self.extract_activity_id():
            return False
        
        self.prepare_form_data(custom_answers)
        return self.submit()


def submit_questionnaire(url: str, user_info: Dict[str, str], 
                        custom_answers: Dict[str, Any] = None) -> bool:
    """
    快捷函数：提交问卷
    
    Args:
        url: 问卷链接
        user_info: 用户信息
        custom_answers: 自定义答案
    
    Returns:
        是否成功
    """
    handler = QuestionnaireHandler(url, user_info)
    return handler.run(custom_answers)

